package com.coldchain.auth.module.client.api;

import com.coldchain.auth.jwt.user.JwtAuthenticationRequest;
import com.coldchain.auth.module.client.service.IAuthService;
import com.coldchain.common.constant.RequestHeaderConstants;
import com.coldchain.common.msg.ObjectRestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AuthController
 * @Description
 * @Author fangliai
 * @Date 2018/8/29 14:45
 * @Vesion 1
 **/

@RestController
@Api("授权服务")
@RequestMapping("/oauth")
public class AuthController {
   @Value("${jwt.token-header}")
   private String tokenHeader;
   @Resource
   private IAuthService authService;


   @ApiOperation(value = "获取token",httpMethod = "POST")
   @ApiImplicitParams({
           @ApiImplicitParam(value = "scope" ,name = "登录域{司机:driver  货主:user 承认:cys  平台:admin }",dataType = "string",required =true,paramType="query"),
           @ApiImplicitParam(value = "username",name = "登录名",dataType = "string",required = true,paramType = "query"),
           @ApiImplicitParam(value = "password",name = "密码",dataType = "string",required = true,paramType = "query")
   })
   @RequestMapping(value = "/token", method = RequestMethod.POST)
   public ObjectRestResponse<String> createAuthenticationToken(HttpServletRequest request, HttpServletResponse response,
          JwtAuthenticationRequest authenticationRequest) throws Exception {
    final String token = authService.login(authenticationRequest);
    if (StringUtils.isBlank(token)) {

     return new ObjectRestResponse<String>().data("");
    }
   Cookie cookie = new Cookie("token", RequestHeaderConstants.JWT_TOKEN_TYPE + token);
   cookie.setPath("/");
   response.addCookie(cookie);
    return new ObjectRestResponse<String>().data(RequestHeaderConstants.JWT_TOKEN_TYPE + token);
   }

    @ApiOperation(value = "异新token",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "Authorization" ,name = "token",dataType = "string",required =true,paramType="header")
    })
   @RequestMapping(value = "refresh", method = RequestMethod.GET)
   public ObjectRestResponse<String> refreshAndGetAuthenticationToken(
           HttpServletRequest request) throws Exception {
    String token = request.getHeader(tokenHeader);
    String refreshedToken = authService.refresh(getRealToken(token));
    return new ObjectRestResponse<String>().data(RequestHeaderConstants.JWT_TOKEN_TYPE + refreshedToken);
   }

    @ApiOperation(value = "验证token",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "token" ,name = "token",dataType = "string",required =true,paramType="query")
    })
   @RequestMapping(value = "verify", method = RequestMethod.GET)
   public ObjectRestResponse<?> verify(String token) throws Exception {
    authService.validate(getRealToken(token));
    return new ObjectRestResponse<Boolean>().data(true);
   }

    @ApiOperation(value = "invalid",httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "token" ,name = "token",dataType = "string",required =true,paramType="query")
    })
   @RequestMapping(value = "invalid", method = RequestMethod.POST)
   public ObjectRestResponse<Boolean> invalid(@RequestParam("token") String token) throws Exception {
    authService.invalid(getRealToken(token));
    return new ObjectRestResponse<Boolean>().data(true);
   }

   /**
    * 获取真正得JWT Token
    * @param originToken
    * @return
    */
   private String getRealToken(String originToken) {
    if (originToken != null && originToken.startsWith(RequestHeaderConstants.JWT_TOKEN_TYPE)) {
     originToken = originToken.substring(RequestHeaderConstants.JWT_TOKEN_TYPE.length(), originToken.length());
    }
    return originToken;
   }
}
